package com.tensquare.user;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * 网建短信发送接口
 * 
 * @author RedDream
 *
 */
public class SendMsg {
	public static final String url = "http://utf8.sms.webchinese.cn";

	public static final String account = "17122030801@163.com";

	public static final String msgKey = "d41d8cd98f00b204e980";

	public static Boolean sendMsg(String phoneNo, String template) {
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(url);
		post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");// 在头文件中设置转码
		NameValuePair[] data = { new NameValuePair("Uid", account), new NameValuePair("Key", msgKey),
				new NameValuePair("smsMob", phoneNo), new NameValuePair("smsText", template) };
		post.setRequestBody(data);

		try {
			client.executeMethod(post);
			post.getResponseHeaders();
			int statusCode = post.getStatusCode();
			// 返回消息状态
			String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
			post.releaseConnection();
			if (statusCode == 200 && "1".equals(result)) {
				return true;
			} else {
				return false;
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		//PathUtil pathUtil = new PathUtil();
		Boolean sendMsg = sendMsg("18688706261", "我只是想测试测试你怎么想的了：" + RandomStringUtils.randomNumeric(6));
		if (sendMsg) {
			System.out.println("短信发送成功！");
		} else {
			System.out.println("短信发送失败！");
		}
	}
}
